package com.tools.common.object.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.tools.common.object.BasicEnum;
import com.tools.common.object.Note;

import java.io.IOException;

/**
 * 基本类型的处理器
 * */
@Note("基本类型的处理器")
public class BasicTypeHandler {

    private BasicTypeHandler() {}

    @Note("对数字做一些处理，若数字范围超过了 JavaScript 能处理的最大值，那就返回字符串，否则返回纯数字")
    public static JsonSerializer<Number> numberSerializer() {
        return new JsonSerializer<Number>() {
            @Override
            public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                if(BasicEnum.isNotInJSMaxRange(number)) {
                    jsonGenerator.writeString(number.toString());
                    return;
                }
                jsonGenerator.writeRawValue(number.toString());
            }
        };
    }
}
